package com.itnoob.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.itnoob.domain.Article;
import com.itnoob.handler.ReviewHandler;
import com.itnoob.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhoujun
 * @date 2025/3/18 21:29
 */
@Service
public class ReviewArticleService {

//    @Autowired
//    private ReviewHandler reviewHandler;

    public Result  reviewArticle(Article article){
        List<ReviewHandler> reviewHandlers = buildHandlers(article);
        Iterator<ReviewHandler> iterator = reviewHandlers.iterator();
        Result result = null;
        while (iterator.hasNext()){
            ReviewHandler reviewHandler = iterator.next();
             result = reviewHandler.review(article);
            if (!result.isApproved()){
                return result;
            }
        }

        //
        article.setApproved(true);

        return result;
    }

    /**
     * 迭代器模式
     * @param article
     * @return
     */
    private List<ReviewHandler> buildHandlers(Article article){

        List<String> split = StrUtil.split(article.getReViewers(), ",");
        List<ReviewHandler> reviewHandlers = split.stream().map(beanName -> (ReviewHandler) SpringUtil.getBean(beanName)).collect(Collectors.toList());
        return reviewHandlers;
    }
}
